#!/bin/bash

if [ $# -lt 1 ]; then
   echo "$0 <project name> [add | remove]"
   exit 1
fi

GROK_ROOT=/export/grok/opengrok-new
URI=http://localhost:443/source
PROJ=$1
ACT=$2
INDEX="yes"

export JAVA_HOME=/usr/lib/jvm/java-11-openjdk
export PATH=${GROK_ROOT}/dist/tools/env/bin:/usr/lib/jvm/java-11-openjdk/bin:$PATH

if [ "$ACT" = "remove" ]; then
  echo "Remove old index"
  opengrok-projadm -b ${GROK_ROOT} -U ${URI} -N -d ${PROJ}
  INDEX="no"

elif [ "$ACT" = "add" ]; then
  echo "Adding project ${PROJ} to configure file"
  opengrok-projadm -b ${GROK_ROOT} -U ${URI} -a ${PROJ}
fi

if [ "X$INDEX" = "Xyes" ]; then
  echo "Indexing project ${PROJ} ..."
  touch ${GROK_ROOT}/src/${PROJ}/.opengrok_skip_history
  curl -s -X GET ${URI}/api/v1/configuration -o fresh_config.xml
  opengrok-indexer -a ${GROK_ROOT}/dist/lib/opengrok.jar -- \
      -c /usr/local/bin/ctags \
      -U ${URI} \
      -R fresh_config.xml \
      --progress \
      -H \
      -L 200 \
      -G \
      ${PROJ}
fi

echo "Refreshing project ${PROJ} ..."
opengrok-projadm -b ${GROK_ROOT} -r -U ${URI}

echo "done!"
